package com.tlgen.utils;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩包工具类
 */
public class ZipUtils {

    /**
     * 生成压缩包
     * @param destFileName
     */
    public static void generatorZip(String sourceFileName, String destFileName) {
        File file = new File(sourceFileName);
        try {
            handleZip(file, destFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void handleZip(File sourceFile, String destFileName) throws IOException {
        FileOutputStream fileOut = null;
        try {
            fileOut = new FileOutputStream(destFileName);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        ZipOutputStream out = new ZipOutputStream(fileOut);
        // 截取最后的路径放入文件 E:\generate\f9346c57-ea26-4659-a51c-c6720b20b4c4
        zip(sourceFile, out, sourceFile.getPath().substring(sourceFile.getPath().lastIndexOf("\\")));
        out.close();
    }

    private static void zip(File sourceFile, ZipOutputStream out, String base)
            throws IOException {

        if (sourceFile.isDirectory()) {
            File[] files = sourceFile.listFiles();
            out.putNextEntry(new ZipEntry(base + "/"));
            base = base.length() == 0 ? "" : base + "/";
            for (File file : files) {
                zip(file, out, base + file.getName());
            }
        } else {
            if (base.length() > 0) {
                out.putNextEntry(new ZipEntry(base));
            } else {
                out.putNextEntry(new ZipEntry(sourceFile.getName()));
            }
//            System.out.println("filepath=" + sourceFile.getPath());
            FileInputStream in = new FileInputStream(sourceFile);

            int b;
            byte[] by = new byte[1024];
            while ((b = in.read(by)) != -1) {
                out.write(by, 0, b);
            }
            in.close();
        }
    }

}
